const config = require('../config'); // 引入配置文件
const myMd5 = require('../utils/md5password'); // 引入加密模块
const CityDao = require('../dao/cityDao'); // 引入数据库
const cityRedis = require('../redis/cityRedis'); // 引入redis

exports.getResourcesInfo = (req, res) => {
    const { userid, sign } = req.query;
    if (userid == null || sign == null) {
        res.send({
            code: 1,
            msg: '参数错误',
        })
        return;
    }
    let mySign = myMd5.md5(userid + req.ip + config.ACCOUNT_KEY);
    if (mySign != sign) {
        res.send({
            code: 1,
            msg: '签名错误',
        })
        return;
    }
    CityDao.getResourcesInfo(userid).then((result) => {
        if (!result) {
            res.send({
                code: 1,
                msg: '没有资源',
            })
        } else {
            // 业务处理
            for (let i = 0; i < result.length; i++) {
                let timeTemp = Date.parse(new Date()) / 1000; // 获取当前时间
                let timeDistance = (timeTemp - result[i].updateTime) / (60 * 60); // 获取时间差
                // 计算累计数量 = 之前的库存 + 增长速率 * 时间差
                let total = parseFloat(result[i].count) + parseFloat(result[i].addRate) * timeDistance;
                // 计算当前库存
                let nowCount = 0;
                let maxCount = result[i].allCount;
                if (total > maxCount) {
                    nowCount = maxCount;
                } else {
                    nowCount = total;
                }
                result[i].count = nowCount; // 更新当前库存
                // 写入redis
                let key = 't_resources' + '_' + userid + '_' + result[i].type;
                cityRedis.setResource(key, result[i], (res) => {
                    if (res) {
                        console.log('redis写入成功');
                    }
                });
            }
            res.send({
                code: 0,
                msg: '获取成功',
                data: result,
            })
        }
    })
}

exports.getBlockData = (req, res) => {
    const { m, n } = req.query;
    if (m == null || n == null) {
        res.send({
            code: 1,
            msg: 'm或n参数错误',
        })
        return;
    }
    CityDao.getBlockData(m, n).then(result => {
        if (result) {
            console.log('result:', result);
            res.send({
                code: 0,
                msg: '获取成功',
                data: result,
            })
        } else {
            res.send({
                code: 1,
                msg: '获取失败',
            })
        }
    });
}